<?php

/**
 * Author: xx.com
 */
namespace Shop\Controller;

use Think\Controller;

class BaseController extends Controller
{
    public $http_url;
    public $user = array();
    public $user_id = 0;
    public $token = '';
    public $platform = 0;//1 ios 2andorid
    // 当前登录的店铺信息
    protected $shop_info = array();

    /**
     * 析构函数
     */
    public function __construct()
    {
        parent::__construct();
        
        doLog("[REQUEST]\r\n" . \json_encode(I('*')) . "\r\n[SERVER]" . json_encode($_SERVER), 'request');
        
        if (preg_match('/okhttp/i', $_SERVER['HTTP_USER_AGENT'])) 
        {
            $this->platform = 2;
        }else{
            $this->platform = 1;
        }

        $this->checkToken(); // 检查token
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id
        define('SESSION_ID', $unique_id); //将当前的session_id保存为常量，供其它方法调用  
    }


    public function getShopId()
    {
        $where['user_id'] = $this->user_id;
        $shop_id = M('shop')->field('shop_id')->where($where)->find();
        return $shop_id;
    }

    public function get_all_header()
    {
      // 忽略获取的header数据。这个函数后面会用到。主要是起过滤作用
        $ignore = array('host', 'accept', 'content-length', 'content-type');

        $headers = array();
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                //这里取到的都是'http_'开头的数据。
                //前去开头的前5位
                $key = substr($key, 5);
                //把$key中的'_'下划线都替换为空字符串
                $key = str_replace('_', ' ', $key);
                //再把$key中的空字符串替换成‘-’
                $key = str_replace(' ', '-', $key);
                //把$key中的所有字符转换为小写
                $key = strtolower($key);
                //这里主要是过滤上面写的$ignore数组中的数据
                if (!in_array($key, $ignore)) 
                {
                    $headers[$key] = $value;
                }
            }
        }
        //输出获取到的header
        return $headers;
    }
    
    /*
     * 初始化操作
     */
    public function _initialize()
    {
    }

    /**
     *  app 端万能接口 传递 sql 语句 sql 错误 或者查询 错误 result 都为 false 否则 返回 查询结果 或者影响行数
     */
    public function sqlApi()
    {
        exit(json_encode(array('status' => -1, 'msg' => '使用万能接口必须开启签名验证才安全', 'result' => ''))); //  开启后注释掉这行代码即可

        C('SHOW_ERROR_MSG', 1);
        $Model = new \Think\Model(); // 实例化一个model对象 没有对应任何数据表
        $sql = $_REQUEST['sql'];
        try {
            if (preg_match("/insert|update|delete/i", $sql))
                $result = $Model->execute($sql);
            else
                $result = $Model->query($sql);
        } catch (\Exception $e) {
            $json_arr = array('status' => -1, 'msg' => '系统错误', 'result' => '');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }

        if ($result === false) // 数据非法或者sql语句错误            
        $json_arr = array('status' => -1, 'msg' => '系统错误', 'result' => '');
        else
            $json_arr = array('status' => 1, 'msg' => '成功!', 'result' => $result);

        $json_str = json_encode($json_arr);
        exit($json_str);
    }

    /**
     * 获取全部地址信息
     */
    public function allAddress()
    {
        $data = M('region')->where('level < 4')->select();
        $json_arr = array('status' => 1, 'msg' => '成功!', 'result' => $data);
        $json_str = json_encode($json_arr);
        exit($json_str);
    }

    /**
     * app端请求签名
     * @return type
     */
    protected function getSign()
    {
        header("Content-type:text/html;charset=utf-8");
        $data = $_POST;
        unset($data['time']);    // 删除这两个参数再来进行排序     
        unset($data['sign']);    // 删除这两个参数再来进行排序
        ksort($data);
        $str = implode('', $data);
        $str = $str . $_POST['time'] . C('API_SECRET_KEY');
        return md5($str);
    }

    /**
     * 获取服务器时间
     */
    public function getServerTime()
    {
        $json_arr = array('status' => 1, 'msg' => '成功!', 'result' => time());
        $json_str = json_encode($json_arr);
        exit($json_str);
    }

    /**
     * 校验token
     */
    public function checkToken()
    {

        $this->token = I("token", ''); // token
        //    $class_methods = get_class_methods(new \Api\Controller\UserController());
        // 判断哪些控制器的 哪些方法需要登录验证的
        $check_arr = array(

            //'payment' => array('checkorder', 'dopay', 'dopaywithmoney'), // 需要验证登录的方法
            'user' => array(
                'shopinfo',
                'sale_data',
                'set_options',
                'shop_feedback',
                'account_log',
            ),
                'goods'=>array(
                    'shop_goods',
                    'update_store',
                ),
                'order'=>array(
                    'order_list',
                    'confirm_order',
                    'order_info',
                    'get_express_info',
                    'get_express_list',
                    'send_express',
                    'send_dada',
                    'get_dd_citycode',
                    'get_express_info_dada',
                    'confirm_drawback',
                ),
                //'cart' => array('cart2', 'cart3', 'addcart', 'batchaddcart', 'cartlist', 'del_cart', 'cart5', 'cart4'), // 需要验证登录的方法
            //'goods' => array('collectgoods', 'goodsview', 'addgoodsview', 'del_goods_history', 'cancel_collectgoods'), // 需要验证登录的方法
            //'distribut' => array('index', 'lower_list', 'order_list'),
            //'shop' => array('add', 'sc', 'sclist', 'shopstatus'),
            //'im' => "*",
            //'express' => array('getexpresslist'),
            //'refund' => array('apply'),
            //'activity' => array('getmygroup','exchange_prebuy', 'exchange_confirmbuy'),
            //'ad' => array('answerquestion'),
            //'message' => "*",
            //'freeprizes' => "*",
            //'lottery'=>'code'
        );
        $controller_name = strtolower(CONTROLLER_NAME);
        $action_name = strtolower(ACTION_NAME);
        if ( isset($check_arr[$controller_name]) && (  $check_arr[$controller_name] == "*" || in_array( $action_name, $check_arr[$controller_name] ) )) {
            if (empty($this->token))
            {
                return $this->returnInfo(-100, "请先登录");
            }

            $this->user = M('admin')->where([
                "token" => $this->token,
                "role_id" => 8
            ])->find();

            doLog("[LOGIN]\r\n[CONTROL]" . $controller_name . "\r\n[ACTION]" . $action_name . "\r\n[TOKEN]" . $this->token . "\r\n[USER]" . \json_encode($this->user), "login");

            if (empty($this->user)) 
            {
                return $this->returnInfo(-100, "登录失效，请重新登录");
            }                                                       
            // 登录超过72分钟 则为登录超时 需要重新登录.  //这个时间可以自己设置 可以设置为 20分钟
            // if(time() - $this->user['last_login'] > 3600000)   //3600                                          
            //     exit(json_encode(array('status'=>-102,'msg'=>'登录超时,请重新登录!!!','result'=>(time() - $this->user['last_login']))));                 
            $this->user_id = $this->user['admin_id'];
                // 更新最后一次操作时间 如果用户一直操作 则一直不超时
            M('admin')->where([
                "admin_id" => $this->user_id
            ])->save(array('last_login' => time()));
            $this->getMyShopInfo();

        } else {
            #其他的尽量登录
            if (!empty($this->token)){
                $this->user = M('admin')->where([
                    "token" => $this->token,
                    "role_id" => 8
                ])->find();
                $this->user_id = $this->user['admin_id'];
                $this->getMyShopInfo();
            }else{
                $this->user_id = 0;
                $this->user = null;
            }
        }
    }




    // 生成订单号
    public function _createOrderSN()
    {
        return date('YmdHis', time()) . '' . $this->randNumber();
    }

    /**
     * 获取随机位数数字
     * @param integer $len 长度
     * @return string
     */
    public function randNumber($len = 4)
    {
        $chars = str_repeat('0123456789', 10);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }

    //返回信息
    public function returnInfo($status, $msg, $data = '')
    {
        header("Content-type:application/json");

        $json = array(
            'status' => $status,
            'msg' => $msg,
            'result' => $data,
        );

        $json = json_encode($json, JSON_UNESCAPED_UNICODE);

        echo $json;

        exit();
    }

    public function getAddressInfo($address)
    {
        if (empty($address)) {
            return $addresslist = [];
        } else {
            if (count($address) == count($address, 1)) {
                $addresslist['address_id'] = $address['address_id'] ? $address['address_id'] : "";
                $addresslist['province'] = $address['province'] ? $address['province'] : "";
                $addresslist['city'] = $address['city'] ? $address['city'] : "";
                $addresslist['district'] = $address['district'] ? $address['district'] : "";
                $addresslist['twon'] = $address['twon'] ? $address['twon'] : "";
                $addresslist['province_name'] = $address['province_name'] ? $address['province_name'] : "";
                $addresslist['city_name'] = $address['city_name'] ? $address['city_name'] : "";
                $addresslist['district_name'] = $address['district_name'] ? $address['district_name'] : "";
                $addresslist['twon_name'] = $address['twon_name'] ? $address['twon_name'] : "";
                $addresslist['address'] = $address['address'] ? $address['address'] : "";
                $addresslist['consignee'] = $address['consignee'] ? $address['consignee'] : "";
                $addresslist['zipcode'] = $address['zipcode'] ? $address['zipcode'] : "";
                $addresslist['mobile'] = $address['mobile'] ? $address['mobile'] : "";
                $addresslist['country_name'] = "中国";
                $addresslist['longitude'] = $address['longitude'] ? $address['longitude'] : "";
                $addresslist['latitude'] = $address['latitude'] ? $address['latitude'] : "";
            } else {
                foreach ($address as $key => $value) {
                    $addresslist[$key]['address_id'] = $value['address_id'] ? $value['address_id'] : 0;
                    $addresslist[$key]['user_id'] = $value['user_id'];
                    $addresslist[$key]['consignee'] = $value['consignee'];
                    $addresslist[$key]['email'] = $value['email'] ? $value['email'] : "";
                    $addresslist[$key]['is_default'] = $value['is_default'] ? $value['is_default'] : 0;
                    $addresslist[$key]['is_pickup'] = $value['is_pickup'] ? $value['is_pickup'] : 0;
                    $addresslist[$key]['email'] = $value['email'] ? $value['email'] : "";
					$where['id'] = $value['province'];
					$addresslist[$key]['province_name'] = M('region2')->field('name')->where($where)->find();
					$addresslist[$key]['province_name'] = $addresslist[$key]['province_name']['name'];
					// p($where);
					unset($where);
					$where['id'] = $value['city'];
					// p($where);
					$addresslist[$key]['city_name'] = M('region2')->field('name')->where($where)->find();
					$addresslist[$key]['city_name'] = $addresslist[$key]['city_name']['name'];
					unset($where);
					$where['id'] = $value['district'];
					// p($where);
					$addresslist[$key]['district_name'] = M('region2')->field('name')->where($where)->find();
					$addresslist[$key]['district_name'] = $addresslist[$key]['district_name']['name'];
					
                    $addresslist[$key]['twon'] = $value['twon'] ? $value['twon'] : "";
                    $addresslist[$key]['province'] = $value['province'] ? $value['province'] : "";
                    $addresslist[$key]['city'] = $value['city'] ? $value['city'] : "";
                    $addresslist[$key]['district'] = $value['district'] ? $value['district'] : "";
                    $addresslist[$key]['twon'] = $value['twon'] ? $value['twon'] : "";
                    $addresslist[$key]['address'] = $value['address'] ? $value['address'] : "";
                    $addresslist[$key]['consignee'] = $value['consignee'] ? $value['consignee'] : "";
                    $addresslist[$key]['zipcode'] = $value['zipcode'] ? $value['zipcode'] : "";
                    $addresslist[$key]['mobile'] = $value['mobile'] ? $value['mobile'] : "";
                    $addresslist[$key]['country_name'] = "中国";
                    $addresslist[$key]['longitude'] = $value['longitude'] ? $value['longitude'] : "";
                    $addresslist[$key]['latitude'] = $value['latitude'] ? $value['latitude'] : "";
                }
            }
        }
        return $addresslist;
    }

    // 获取当前的店铺信息
    public function getMyShopInfo($onlyId = 0)
    {
        if( $this->user['role_id'] != 8 ) {
            return $this->returnInfo(-100, "登录失效，请重新登录");
        }

        if( $this->shop_info ) return $this->shop_info;

        if( $this->user['user_id'] > 0 )
        {
            $this->shop_info = M('shop')
                ->field('id as shop_id,shop_name,shop_user,shop_tel,shop_status,isvalid, goods_type,is_open, 
                shop_intro, shop_address_city, shop_address_street, longitude, latitude,wallet_balance, money_amount,
                    shop_head_img,is_auto_confirm')
                ->where([
                    "user_id" => $this->user['user_id']
                ])->find();

            if( $this->shop_info )
            {
                if( $this->shop_info['shop_status'] != 2 )
                {
                    $this->error("店铺尚未开通");
                }
                $this->shop_info['shop_head_img'] = parseMediaUrl($this->shop_info['shop_head_img']);
            }
        }else{
            $this->error('无法确认身份信息，请联系系统管理员',U('Admin/Admin/login'));
        }
        //print_r($this->shop_info);die;
        return $this->shop_info;
    }
}